package luongvd.appview;

import luongvd.appview.common.utils.ServerConnectionUtils;
import luongvd.appview.model.Delegate.ServerDelegate;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	Context mContext;
	WebView webView;
	String appPackageName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_main);
		initView();
		ServerDelegate.connectServer(handler, ServerDelegate.LINK_GET_URL);
	}

	@SuppressLint("SetJavaScriptEnabled")
	void initView() {
		webView = (WebView) findViewById(R.id.webView);
		webView.setWebViewClient(new AppWebViewClients());
		webView.getSettings().setJavaScriptEnabled(true);
	}

	public class AppWebViewClients extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			startNewActivity(mContext, appPackageName);
			ServerDelegate.connectServer(handler, ServerDelegate.LINK_SET_DONE);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			ServerDelegate.connectServer(handler, ServerDelegate.LINK_SET_DONE);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			Toast.makeText(mContext, "OnReceivedError: " + errorCode,
					Toast.LENGTH_LONG).show();
		}
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == ServerConnectionUtils.CONNECT_TO_SERVER_MESSAGE_SUCCESSFUL) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					String keyAction = dataJSONObject.getString("action");
					String keyStatus = dataJSONObject.getString("status");
					if (keyAction.equals("getLink")) {
						if (Integer.parseInt(keyStatus) > 0) {
							JSONObject jsonData = new JSONObject();
							jsonData = dataJSONObject.getJSONObject("data");
							appPackageName = jsonData.getString("link");
							String url = "http://play.google.com/store/apps/details?id="
									+ appPackageName;
							webView.loadUrl(url);
						}
					} else if (keyAction.equals("setDone")) {
						Toast.makeText(
								mContext,
								"View Successful",
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					Toast.makeText(mContext, "Error when connect to server",
							Toast.LENGTH_LONG).show();
				}
			}
		}
	};
	
	public void startNewActivity(Context context, String packageName) {
	    Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
	    if (intent != null) {
	        /* We found the activity now start the activity */
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        startActivity(intent);
	    } else {
	        /* Bring user to the market or let them choose an app? */
	        intent = new Intent(Intent.ACTION_VIEW);
	        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        intent.setData(Uri.parse("market://details?id=" + packageName));
	        startActivity(intent);
	    }
	}
}
